{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-08-04T15:52:55.449491Z",
     "start_time": "2020-08-04T15:52:30.896579Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.1.0\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "print(tf.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 池化层\n",
    "\n",
    "回忆一下，在[“二维卷积层”](conv-layer.ipynb)一节里介绍的图像物体边缘检测应用中，我们构造卷积核从而精确地找到了像素变化的位置。设任意二维数组`X`的`i`行`j`列的元素为`X[i, j]`。如果我们构造的卷积核输出`Y[i, j]=1`，那么说明输入中`X[i, j]`和`X[i, j+1]`数值不一样。这可能意味着物体边缘通过这两个元素之间。但实际图像里，我们感兴趣的物体不会总出现在固定位置：即使我们连续拍摄同一个物体也极有可能出现像素位置上的偏移。这会导致同一个边缘对应的输出可能出现在卷积输出`Y`中的不同位置，进而对后面的模式识别造成不便。\n",
    "\n",
    "在本节中我们介绍池化（pooling）层，它的提出是为了缓解卷积层对位置的过度敏感性。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5.4.1 2-dimentional max_pooling and avg_pooling\n",
    "\n",
    "同卷积层一样，池化层每次对输入数据的一个固定形状窗口（又称池化窗口）中的元素计算输出。不同于卷积层里计算输入和核的互相关性，池化层直接计算池化窗口内元素的最大值或者平均值。该运算也分别叫做最大池化或平均池化。在二维最大池化中，池化窗口从输入数组的最左上方开始，按从左往右、从上往下的顺序，依次在输入数组上滑动。当池化窗口滑动到某一位置时，窗口中的输入子数组的最大值即输出数组中相应位置的元素。\n",
    "\n",
    "![池化窗口形状为$2\\times 2$的最大池化](../img/pooling.svg)\n",
    "\n",
    "图5.6展示了池化窗口形状为$2\\times 2$的最大池化，阴影部分为第一个输出元素及其计算所使用的输入元素。输出数组的高和宽分别为2，其中的4个元素由取最大值运算$\\text{max}$得出：\n",
    "\n",
    "$$\n",
    "\\max(0,1,3,4)=4,\\\\\n",
    "\\max(1,2,4,5)=5,\\\\\n",
    "\\max(3,4,6,7)=7,\\\\\n",
    "\\max(4,5,7,8)=8.\\\\\n",
    "$$\n",
    "\n",
    "\n",
    "二维平均池化的工作原理与二维最大池化类似，但将最大运算符替换成平均运算符。池化窗口形状为$p \\times q$的池化层称为$p \\times q$池化层，其中的池化运算叫作$p \\times q$池化。\n",
    "\n",
    "让我们再次回到本节开始提到的物体边缘检测的例子。现在我们将卷积层的输出作为$2\\times 2$最大池化的输入。设该卷积层输入是`X`、池化层输出为`Y`。无论是`X[i, j]`和`X[i, j+1]`值不同，还是`X[i, j+1]`和`X[i, j+2]`不同，池化层输出均有`Y[i, j]=1`。也就是说，使用$2\\times 2$最大池化层时，只要卷积层识别的模式在高和宽上移动不超过一个元素，我们依然可以将它检测出来。\n",
    "\n",
    "下面把池化层的前向计算实现在`pool2d`函数里。它跟[“二维卷积层”](conv-layer.ipynb)一节里`corr2d`函数非常类似，唯一的区别在计算输出`Y`上。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-08-04T15:53:02.519653Z",
     "start_time": "2020-08-04T15:53:02.513670Z"
    }
   },
   "outputs": [],
   "source": [
    "def pool2d(X, pool_size, mode='max'):\n",
    "    p_h, p_w = pool_size\n",
    "    Y = tf.zeros((X.shape[0] - p_h + 1, X.shape[1] - p_w +1))\n",
    "    Y = tf.Variable(Y)\n",
    "    for i in range(Y.shape[0]):\n",
    "        for j in range(Y.shape[1]):\n",
    "            if mode == 'max':\n",
    "                Y[i,j].assign(tf.reduce_max(X[i:i+p_h, j:j+p_w]))\n",
    "            elif mode =='avg':\n",
    "                Y[i,j].assign(tf.reduce_mean(X[i:i+p_h, j:j+p_w]))\n",
    "    return Y"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们可以构造图5.6中的输入数组`X`来验证二维最大池化层的输出。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-08-04T15:53:03.537969Z",
     "start_time": "2020-08-04T15:53:03.402295Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Variable 'Variable:0' shape=(2, 2) dtype=float32, numpy=\n",
       "array([[4., 5.],\n",
       "       [7., 8.]], dtype=float32)>"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = tf.constant([[0,1,2],[3,4,5],[6,7,8]],dtype=tf.float32)\n",
    "pool2d(X, (2,2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "同时我们实验一下平均池化层。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Variable 'Variable:0' shape=(2, 2) dtype=float32, numpy=\n",
       "array([[2., 3.],\n",
       "       [5., 6.]], dtype=float32)>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pool2d(X, (2,2), 'avg')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5.4.2 padding and stride\n",
    "\n",
    "同卷积层一样，池化层也可以在输入的高和宽两侧的填充并调整窗口的移动步幅来改变输出形状。池化层填充和步幅与卷积层填充和步幅的工作机制一样。我们将通过`nn`模块里的二维最大池化层MaxPool2D来演示池化层填充和步幅的工作机制。我们先构造一个形状为(1, 1, 4, 4)的输入数据，前两个维度分别是批量和通道。\n",
    "\n",
    "注：tensorflow默认数据类型为'channels_last'，所以这里使用(1,4,4,1)而不是(1,1,4,4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-08-04T15:53:06.321492Z",
     "start_time": "2020-08-04T15:53:06.315507Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor: shape=(1, 4, 4, 1), dtype=int32, numpy=\n",
       "array([[[[ 0],\n",
       "         [ 1],\n",
       "         [ 2],\n",
       "         [ 3]],\n",
       "\n",
       "        [[ 4],\n",
       "         [ 5],\n",
       "         [ 6],\n",
       "         [ 7]],\n",
       "\n",
       "        [[ 8],\n",
       "         [ 9],\n",
       "         [10],\n",
       "         [11]],\n",
       "\n",
       "        [[12],\n",
       "         [13],\n",
       "         [14],\n",
       "         [15]]]])>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#tensorflow default data_format == 'channels_last'\n",
    "#so (1,4,4,1) instead of (1,1,4,4)\n",
    "X = tf.reshape(tf.constant(range(16)), (1,4,4,1))\n",
    "X"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "默认情况下，`MaxPool2D`实例里步幅和池化窗口形状相同。下面使用形状为(3, 3)的池化窗口，默认获得形状为(3, 3)的步幅。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor: id=113, shape=(1, 1, 1, 1), dtype=int32, numpy=array([[[[10]]]])>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pool2d = tf.keras.layers.MaxPool2D(pool_size=[3,3])\n",
    "pool2d(X)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor: id=114, shape=(1, 2, 2, 1), dtype=int32, numpy=\n",
       "array([[[[10],\n",
       "         [11]],\n",
       "\n",
       "        [[14],\n",
       "         [15]]]])>"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#I guess no custom padding settings in keras.layers?\n",
    "pool2d = tf.keras.layers.MaxPool2D(pool_size=[3,3],padding='same',strides=2)\n",
    "pool2d(X)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5.4.3 multi-channels\n",
    "\n",
    "在处理多通道输入数据时，池化层对每个输入通道分别池化，而不是像卷积层那样将各通道的输入按通道相加。这意味着池化层的输出通道数与输入通道数相等。下面将数组`X`和`X+1`在通道维上连结来构造通道数为2的输入。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-08-04T15:53:20.314011Z",
     "start_time": "2020-08-04T15:53:20.309066Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "TensorShape([1, 4, 4, 2])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = tf.concat([X, X+1], axis=3)\n",
    "X.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-08-04T15:53:22.265794Z",
     "start_time": "2020-08-04T15:53:22.255821Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor: shape=(1, 2, 2, 2), dtype=int32, numpy=\n",
       "array([[[[10, 11],\n",
       "         [11, 12]],\n",
       "\n",
       "        [[14, 15],\n",
       "         [15, 16]]]])>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pool2d = tf.keras.layers.MaxPool2D(3, padding='same', strides=2)\n",
    "pool2d(X)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 小结\n",
    "\n",
    "* 最大池化和平均池化分别取池化窗口中输入元素的最大值和平均值作为输出。\n",
    "* 池化层的一个主要作用是缓解卷积层对位置的过度敏感性。\n",
    "* 可以指定池化层的填充和步幅。\n",
    "* 池化层的输出通道数跟输入通道数相同。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": true,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
